package com.yonyou.crm.tpub.excel.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.tpub.excel.entity.ExcelDataRuleVO;
import com.yonyou.crm.tpub.excel.entity.ExcelDataTypeEnum;
import com.yonyou.crm.tpub.excel.entity.ExcelTemplateVO;

@Service
public class ExcelBizServiceImpl extends BaseBizServiceImpl<ExcelTemplateVO> {

	/**
	 * 根据名称获得值
	 * @param dataType
	 * @param ruleVO
	 * @param cellValue
	 * @return
	 */
	public String getValueByName(int dataType, ExcelDataRuleVO ruleVO, String cellValue) {
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		
		String columns = "id";
		String tableName = "";
		List<Map<String, Object>> whereList = new ArrayList<Map<String,Object>>();
		
		if (ExcelDataTypeEnum.REF.getValue() == dataType) {
			
			tableName = ruleVO.getRefTableName();
			
			Map<String, Object> whereMap = new HashMap<String, Object>();
			//大小写敏感
			whereMap.put("whereColumn", "binary " + ruleVO.getRefColumnName());
			whereMap.put("whereValue", cellValue);
			whereList.add(whereMap);
		}
		else if (ExcelDataTypeEnum.ENUM.getValue() == dataType) {

			columns = "value";
			tableName = "sys_enum";
			
			Map<String, Object> codeMap = new HashMap<String, Object>();
			codeMap.put("whereColumn", "code");
			codeMap.put("whereValue", ruleVO.getEnumCode());
			whereList.add(codeMap);
			
			Map<String, Object> nameMap = new HashMap<String, Object>();
			nameMap.put("whereColumn", "name");
			nameMap.put("whereValue", cellValue);
			whereList.add(nameMap);
		}
		else if (ExcelDataTypeEnum.DOC.getValue() == dataType) {
			
			tableName = "base_doc_detail";
			
			Map<String, Object> docMap = new HashMap<String, Object>();
			docMap.put("whereColumn", "base_doc_id");
			docMap.put("whereValue", ruleVO.getEnumCode());
			whereList.add(docMap);
			
			Map<String, Object> nameMap = new HashMap<String, Object>();
			nameMap.put("whereColumn", "name");
			nameMap.put("whereValue", cellValue);
			whereList.add(nameMap);
		}
		
		if (StringUtils.isBlank(tableName)) {
			throw new CrmBusinessException("获取Excel单元格值的表名不能为空");
		}
		
		paraMap.put("columns", columns);
		paraMap.put("tableName", tableName);
		paraMap.put("whereList", whereList);
		
		return (String)dao.selectOne(ExcelTemplateVO.class, "getValueByName", paraMap);
	}
	
}
